﻿/**
 * 站内消息管理
 */


layui.define(['table', 'form'], function (exports) {
    var $ = layui.$
        , admin = layui.admin
        , setter = layui.setter
        , view = layui.view
        , table = layui.table
        , form = layui.form;

    var messageBody = '';

    function getMessageDetail(id) {
        let msgDetail;
        $.ajax({
            url: setter.baseConfig.apiHost + '/api/message/detail?id=' + id //实际使用请改成服务端真实接口
            , type: 'get'
            , async: false //同步请求
            , contentType: "application/json"
            //, data: JSON.stringify(field)
            , beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
            }
            , success: function (res) {
                if (res.errorCode != '00000') {
                    return;
                }

                msgDetail = res.data;
            }
        });

        return msgDetail;
    }

    //事件
    var active = {
        add: function () {
            var index1 = admin.popup({
                title: '添加站内消息'
                , area: ['800px', '600px']
                , id: 'LAY-popup-message-add'
                , success: function (layero, index) {
                    view(this.id).render('sysmanage/msgform').done(function () {
                        form.render(null, 'layuiadmin-form-messageadmin');

                        //初始化Quill
                        const quill = new Quill('#message_editor', {
                            modules: {
                                toolbar: [
                                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                                    ['bold', 'italic'],
                                    ['link', 'blockquote', 'code-block', 'image'],
                                    [{ list: 'ordered' }, { list: 'bullet' }],
                                    [{ 'color': [] }, { 'background': [] }],
                                    ['clean'],
                                ],
                            },
                            placeholder: '请输入正文...',
                            theme: 'snow',
                        });

                        //开启提交
                        form.on('submit(LAY-message-front-submit)', function (data) {
                            //获取Quill编辑器的内容
                            var quillContent = JSON.stringify(quill.getContents().ops);
                            data.field['body'] = quillContent;

                            //获取Quill编辑器的HTML
                            var contentHtml = quill.getSemanticHTML(0);
                            console.log(contentHtml);
                            data.field['bodyHtml'] = contentHtml;

                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            $.ajax({
                                url: setter.baseConfig.apiHost + '/api/message/add' //实际使用请改成服务端真实接口
                                , type: 'post'
                                , contentType: "application/json"
                                , data: JSON.stringify(data.field)
                                , beforeSend: function (xhr) {
                                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                }
                                , success: function (res) {
                                    if (res.errorCode != '00000') {
                                        layer.msg(res.errorMessage, {
                                            offset: '15px'
                                            , icon: 2
                                            , time: 3000
                                        });

                                        return false;
                                    }

                                    //登入成功的提示与跳转
                                    layer.msg('添加成功', {
                                        offset: '15px'
                                        , icon: 1
                                        , time: 3000
                                    });

                                    layui.table.reload('LAY-message-manage'); //重载表格
                                    layer.close(index1);
                                }
                            });
                        });
                    });
                }
            });

            //最大化
            layer.full(index1);
        }
    };

    $('.layui-btn.layuiadmin-btn-useradmin').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    layui.data.sendParams = function (params) {
        messageBody = params.body;
    }

    //消息管理
    table.render({
        elem: '#LAY-message-manage'
        , url: setter.baseConfig.apiHost + '/api/message/getpagingmessages'
        , method: 'post'
        , contentType: "application/json"
        , headers: { //通过 request 头传递
            Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
        }
        , parseData: function (res) { // res 即为原始返回的数据
            return {
                "code": res.errorCode, // 解析接口状态
                "msg": res.errorMessage, // 解析提示文本
                "count": res.data.totalCount, // 解析数据长度
                "data": res.data.entities // 解析数据列表
            };
        }
        , cols: [[
            { type: 'numbers', fixed: 'left' }
            , { field: 'id', title: 'Id', hide: true }
            , { field: 'createdTime', title: '创建时间', maxWidth: 200 }
            , { field: 'title', title: '标题' }
            , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-message-webuser' }
        ]]
        , page: true
        , limit: 30
        , limits: [10, 20, 30, 40, 50]
        //, height: 'full-320'
        , text: { none: '无数据' }
    });

    //依据用户身份显示和隐藏列
    $.ajax({
        url: setter.baseConfig.apiHost + '/api/user/getloginuserinfo' //实际使用请改成服务端真实接口
        , type: 'post'
        , contentType: "application/json"
        //, data: JSON.stringify(field)
        , beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
        }
        , success: function (res) {
            if (res.errorCode != '00000') {
                layer.msg(res.errorMessage, {
                    offset: '15px'
                    , icon: 2
                    , time: 3000
                });
                return false;
            }

            var role = res.data.role;
            if (role != 'ADMIN') {
                table.hideCol('LAY-message-manage', {
                    field: 'phoneNumber', // 对应表头的 field 属性值
                    hide: true // `true` or `false`
                });
            }
        }
    });

    //工具条
    table.on('tool(LAY-message-manage)', function (obj) {
        var data = obj.data;

        //依据消息id获取消息详情
        var msgDetail = getMessageDetail(data.id);
        //console.log(msgDetail);

        if (obj.event === 'del') {
            layer.confirm('确定要删除吗？', function (index) {
                $.ajax({
                    url: setter.baseConfig.apiHost + '/api/message/remove?id=' + data.id
                    , type: 'get'
                    , contentType: "application/json"
                    //, data: JSON.stringify(data)
                    , beforeSend: function (xhr) {
                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                    }
                    , success: function (res) {
                        if (res.errorCode != '00000') {
                            layer.msg(res.errorMessage, {
                                offset: '15px'
                                , icon: 2
                                , time: 3000
                            });

                            return false;
                        }

                        //登入成功的提示与跳转
                        layer.msg('删除成功', {
                            offset: '15px'
                            , icon: 1
                            , time: 3000
                        });

                        layui.table.reload('LAY-message-manage'); //重载表格
                        layer.close(index); //执行关闭
                    }
                });
            });
        }
        else if (obj.event === 'edit') {
            var editIndex = admin.popup({
                title: '编辑站内消息'
                , area: ['800px', '600px']
                , id: 'LAY-popup-message-add'
                , success: function (layero, index) {
                    view(this.id).render('sysmanage/msgform', msgDetail).done(function () {
                        form.render(null, 'layuiadmin-form-messageadmin');

                        //初始化Quill
                        const quill = new Quill('#message_editor', {
                            modules: {
                                toolbar: [
                                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                                    ['bold', 'italic'],
                                    ['link', 'blockquote', 'code-block', 'image'],
                                    [{ list: 'ordered' }, { list: 'bullet' }],
                                    [{ 'color': [] }, { 'background': [] }],
                                    ['clean'],
                                ],
                            },
                            placeholder: '请输入正文...',
                            theme: 'snow',
                        });

                        //Quill赋值
                        var bodyObj = JSON.parse(messageBody);
                        quill.setContents(bodyObj);

                        //提交
                        form.on('submit(LAY-message-front-submit)', function (data) {
                            //获取Quill编辑器的内容
                            var quillContent = JSON.stringify(quill.getContents().ops);
                            data.field['body'] = quillContent;

                            //获取Quill编辑器的HTML
                            var contentHtml = quill.getSemanticHTML(0);
                            console.log(contentHtml);
                            data.field['bodyHtml'] = contentHtml;

                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            $.ajax({
                                url: setter.baseConfig.apiHost + '/api/message/update' //实际使用请改成服务端真实接口
                                , type: 'post'
                                , contentType: "application/json"
                                , data: JSON.stringify(field)
                                , beforeSend: function (xhr) {
                                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                }
                                , success: function (res) {
                                    if (res.errorCode != '00000') {
                                        layer.msg(res.errorMessage, {
                                            offset: '15px'
                                            , icon: 2
                                            , time: 3000
                                        });

                                        return false;
                                    }

                                    //登入成功的提示与跳转
                                    layer.msg('修改成功', {
                                        offset: '15px'
                                        , icon: 1
                                        , time: 3000
                                    });

                                    layui.table.reload('LAY-message-manage'); //重载表格
                                    layer.close(editIndex); //执行关闭
                                }
                            });
                        });
                    });
                }
            });

            //最大化
            layer.full(editIndex);
        }
    });

    exports('msg', {})
});